<?php

/**
 * 登录处理模块
 * Class LoginController
 *
 */
class LoginController extends Controller
{
    //模型
    private $db;

    /**
     * 构造函数
     */
    public function __init()
    {
        $this->db = M('admin');
        /**
         * 已经登录用户不允许执行
         */
        if (session("uid") && ACTION != 'out') {
            go("Index/index");
        }
        
    }

    /**
     * 登录页面显示验证码
     *
     * @access public
     */
    public function code()
    {
        C(array(
                "CODE_BG_COLOR" => "#ffffff", "CODE_LEN" => 4,
                "CODE_FONT_SIZE" => 20, "CODE_WIDTH" => 120,
                "CODE_HEIGHT" => 35,
            )
        );
        $code = new Code();
        $code->show();
        exit;
    }

    //用户登录处理
    public function index()
    {
        if (IS_POST) {
            $data['code']     = Q('post.code');
            $data['username'] = Q('post.username');
            $data['password'] = Q('post.password');
            if (empty($data['code'])) {
                $this->error('验证码不能为空');
            } else if (strtoupper($data['code']) !== session('code')) {
               $this->error('验证码输入错误');
            }
            if(empty($data['username']) || empty($data['password']) ){
                $this->error('密码或者用户名不能为空');
            }
            $where=array('username' => $data['username'] ,'password' =>md5($data['password']) );
            $user = $this->db->where($where)->find();
            if(!$user){
                $this->error('密码或者用户名不正确');
            }
            session("uid",$user['uid']);
            session("username",$user['username']);
            session('islogin',1);
            $this->log();

            go("Index/index");
        } else {
            $this->display();
        }
    }

     /**
     * 更改登录信息
     */
    public function log()
    {
        $data = array(
            'uid'       => session("uid"),
            'logintime' => time(),
            'loginip'    => ip_get_client()
        );

        return $this->db->save($data);
    }

    /**
     * 退出
     */
    public function out()
    {
        //清空SESSION
        session_unset();
        session_destroy();
        echo "<script>
            window.top.location.href='" . U("index") . "';
        </script>";
        exit;
    }

}
